import { DatabaseOutlined, EllipsisOutlined, FileOutlined, FormOutlined, FullscreenOutlined, KeyOutlined, LockOutlined, PlusOutlined, RollbackOutlined, SearchOutlined, UploadOutlined } from "@ant-design/icons";
import { useEffect, useState } from "react";
import { Menu, message, Popover } from "antd";
import MenuItem from "antd/es/menu/MenuItem";
import AddKnowledgeBase from "./adddata/AddKnowledgeBase";
import DataSet from "./dataset/DataSet";
import { ShowType } from "@/service/general/enumType";
import { isLoggedIn } from "@/service/axiosManager";
import { useMainContentContext } from "@/service/general/publicStatic";
import { KnowledgeBaseModal } from "@/service/request/modal/dataModal";
import { CloseSvg, DeleteSvg } from "../assets/CustomizeSvg";
import { deleteKnowledgeBase, getDatasetModels, getKnowledgeBaseList, isBindKnowledgeBase } from "@/service/request/requestApi";

import "./knowledgebase.css";
import { ResponseModal } from "@/service/request/modal/responseModal";

export default function KnowledgeBaseView() {
    const [knowledgeBaseDatas, setKnowledgeBaseDatas] = useState<KnowledgeBaseModal[]>();
    const [knowledgeBaseEdit, setKnowledgeBaseEdit] = useState<boolean>(false);
    const [knowledgeBaseAdd, setKnowledgeBaseAdd] = useState<boolean>(false);
    const [knowledgeBaseDetail, setKnowledgeBaseDetail] = useState<boolean>(false);
    const [detailItem, setDetailItem] = useState<KnowledgeBaseModal>();
    const [confirmDelete, setConfirmDelete] = useState<boolean>(false);
    const [deleteData, setDeleteData] = useState<KnowledgeBaseModal>();
    const [deleteTip, setDeleteTip] = useState<string>('');

    const [knowledgeBaseEditType, setKnowledgeBaseEditType] = useState<ShowType>(ShowType.CREATE);

    const [searchInputFocus, setSearchInputFocus] = useState<boolean>(false);
    const [loadData, setLoadData] = useState<boolean>(true);
    const {to} = useMainContentContext();

    useEffect(() => {
        Initialize();
    });

    const Initialize = () => {
        if (isLoggedIn() && loadData) {
            setLoadData(false);
            loadDataset();
        }
    }

    const Dispose = () => {
        setKnowledgeBaseDatas(undefined);
    }

    const loadDataset = () => {
        getKnowledgeBaseList().then((res) => {
            if (res.code === 0 && res.success) {
                setKnowledgeBaseDatas(res.result);
            }
        }).catch((error) => {
            console.error(error);
        });
    }

    const removeOption = (removeItem: KnowledgeBaseModal) => {
        if (!removeItem || !removeItem.id) return;
        const param = {
            id: removeItem.id
        }
        isBindKnowledgeBase(param).then((res: ResponseModal<boolean>) => {
            if (res.code === 200 && res.success) {
                removeDataset(removeItem.id);
                return;
            } else if (res.code === 0 && !res.success) {
                setDeleteData(removeItem);
                setDeleteTip(res.message);
                setConfirmDelete(true);
                return;
            } else {
                message.error(res.message || "获取引用验证失败，未知错误");
            }
        }).catch((err) => {
            console.log("获取知识库引用验证失败\n", err);
        });
    }

    const removeDataset = (id: string) => {
        deleteKnowledgeBase(id).then((res) => {
            if (res.code === 200 && res.success) {
                loadDataset();
            }
        }).catch((error) => {
            console.error(error);
        });
    }

    const editDataset = (item: KnowledgeBaseModal) => {
        setDetailItem(item);
        setKnowledgeBaseEditType(ShowType.UPDATE);
        setKnowledgeBaseEdit(true);
    }

    const showDetail = (item: KnowledgeBaseModal) => {
        setDetailItem(item);
        setKnowledgeBaseDetail(true);
    }

    const toDetail = (item: KnowledgeBaseModal) => {
        const detail = <DataSet data={item} />;
        to(detail);
    }

    return (
    <>
    <div className="dataset-view text-black">
        {/* <div className="title">
            <div className="title-text">知识库管理</div>
            <div className="title-close" onClick={() => setOpen(false)}>
                <RollbackOutlined className="icon-close" />
                关闭
            </div>
        </div> */}
        <div className="search">
            <div className="context-title">我的知识库</div>
            <div className="search-input">
                <div className="search-input-box hover:border hover:border-[#0D6EFD]/60" style={searchInputFocus ? {
                    borderWidth: "1px",
                    borderColor: "rgba(13, 110, 253, 0.6)",
                    boxShadow: '0 0 5px rgba(13,110,253, 0.4)',
                }:{}}>
                    <SearchOutlined className="icon-search" />
                    <input type="text" 
                    onFocus={() => setSearchInputFocus(true)} 
                    onBlur={() => setSearchInputFocus(false)}
                    placeholder="知识库名称" />
                </div>
                <div className="new-data" onClick={() => {setKnowledgeBaseEdit(true);}}>
                    <div className="icon-container"><PlusOutlined className="icon-add" /></div>
                    <div className="text-add">新建</div>
                </div>
            </div>
        </div>
        <div className="context">
            {
                knowledgeBaseDatas && knowledgeBaseDatas.length > 0 ? knowledgeBaseDatas.map((item, index) => (
                    <div className="card-data" key={`dataset_list_${item.id}`} onClick={() => {toDetail(item)}}>
                        <div className="card-data-title">
                            <div className="title-info">
                                <div className="icon-title"><DatabaseOutlined className="icon-data-title" /></div>
                                <div className="data-name">{item.name}</div>
                            </div>
                            {/* <div className="data-tag">
                                <div className="icon-tag"><DatabaseOutlined className="icon-data-tag" /></div>
                                <div className="tag-value">{item.type}</div>
                            </div> */}
                        </div>
                        <div className="card-data-desc">
                            {item.intro || "这个知识库还没有介绍~"}
                        </div>
                        <div className="card-data-attr">
                            <div className="data-type card-bottom">
                                {/* <div className="icon-type">
                                    <LockOutlined className="bottom-icon" />
                                </div>
                                <div className="type-value">私有</div> */}
                            </div>
                            <div className="card-menu">
                                <Popover content={<Menu style={{border: "0px"}}>
                                    {/* <MenuItem onClick={() => {editDataset(item);}}>
                                        <div className="menu-item-icon"><FormOutlined /></div>
                                        <span>编辑</span>
                                    </MenuItem> */}
                                    {/* <MenuItem>
                                        <div className="menu-item-icon"><FullscreenOutlined rotate={45} /></div>
                                        <span>移动</span>
                                        
                                    </MenuItem>
                                    <MenuItem>
                                        <div className="menu-item-icon"><KeyOutlined /></div>
                                        <span>权限</span>
                                    </MenuItem>
                                    <hr 
                                        style={{
                                            border: 0,
                                            height: '1px',
                                            background: '#e0e0e0',
                                            margin: '2px 0'
                                        }}
                                    />
                                    <MenuItem>
                                        <div className="menu-item-icon"><UploadOutlined /></div>
                                        <span>导出</span>
                                    </MenuItem>
                                    <hr 
                                        style={{
                                            border: 0,
                                            height: '1px',
                                            background: '#e0e0e0',
                                            margin: '2px 0'
                                        }}
                                    /> */}
                                    <MenuItem>
                                        <div className="w-full h-full flex flex-row items-center justify-center" onClick={(event) => {event.stopPropagation();removeOption(item);}}>
                                            <div className="menu-item-icon menu-delete"><DeleteSvg width={`100%`} height={`100%`} /></div>
                                            <span className="menu-delete">删除</span>
                                        </div>
                                    </MenuItem>
                                </Menu>} arrow={false} trigger="hover" placement="bottomLeft" getPopupContainer={(node) => node}>
                                    {/* <div className="data-model card-bottom">
                                        <div className="icon-model ">
                                            <FileOutlined className="bottom-icon" />
                                        </div>
                                        <div className="model-value">{item.vectorModel}</div>
                                    </div> */}
                                    <div className="text-menu">...</div>
                                </Popover>
                            </div>
                        </div>
                    </div>
                )):(<div>暂无数据</div>)
            }
        </div>
    </div>
    {
        confirmDelete ? (<>
            <DeleteConfirm data={deleteData} setOpen={setConfirmDelete} callback={removeDataset} tip={deleteTip}/>
        </>):(<></>)
    }
    <AddKnowledgeBase open={knowledgeBaseEdit} setOpen={setKnowledgeBaseEdit} showType={knowledgeBaseEditType} callback={loadDataset} />
</>
);
}

const DeleteConfirm = ({
    data,
    tip,
    setOpen,
    callback,
}:{
    data?: KnowledgeBaseModal,
    tip?: string,
    setOpen: (open: boolean) => void,
    callback?: (param?: any) => void,
}) => {

    const closeWindow = () => {
        setOpen(false);
    }

    const submitDelete = () => {
        if (!data?.id) {
            message.error("信息错误，请关闭后重试操作");
            return;
        }
        if (callback) {
            callback(data.id);
        }
    }

    return (<>
        <div className="fixed top-0 left-0 w-screen h-screen flex flex-row items-start justify-center bg-black/20 text-black py-44">
            <div 
            className="w-fit h-fit flex flex-col items-center justify-center gap-3 py-3 bg-white rounded-lg border border-red-300 shadow-[0_0_2px] shadow-red-300" 
            onClick={(e) => e.stopPropagation()}
            onMouseDown={(e) => e.stopPropagation()}
            >
                <div className="w-full flex flex-row items-center justify-between px-4 pb-3 border-b border-b-gray-300">
                    <div className="select-none">删除确认</div>
                    <div className="w-8 h-8 p-1 transition-all duration-300 text-gray-600 hover:rotate-90 hover:bg-gray-300 rounded-lg cursor-pointer" onClick={closeWindow}>
                        <CloseSvg width={`100%`} height={`100%`} />
                    </div>
                </div>
                <div className="w-full flex flex-col items-center justify-center gap-3 px-4">
                    <div>
                        知识库<span className="px-1 mx-1 font-bold border-b-2 border-b-red-300 rounded-ss-md rounded-se-md cursor-pointer select-none hover:bg-gray-200">{data?.name}</span>{tip ? tip : "已被引用，是否继续删除？"}
                    </div>
                    <div className="w-full flex flex-row items-center justify-end gap-3">
                        <div className="px-4 py-2 text-red-600 border border-red-300 rounded-lg cursor-pointer select-none hover:bg-red-100" onClick={submitDelete}>确认删除</div>
                        <div className="px-4 py-2 text-black border border-gray-300 rounded-lg cursor-pointer select-none hover:bg-gray-200" onClick={closeWindow}>取消</div>
                    </div>
                </div>
            </div>
        </div>
    </>);
}